package com.demo.xzbd;

import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * sun 2017-10-31.
 */
@NoRepositoryBean
public interface  BaseRepository<M extends BaseDocument,ID extends Serializable> extends PagingAndSortingRepository<M,ID>{

    default Long count(MongoTemplate mongoTemplate,Query query,Class<M> documentClass) {
        return mongoTemplate.count(query, documentClass);
    }

    default Page<M> findAll(MongoTemplate mongoTemplate, Pageable pageable,Query query,Class<M> documentClass){
        if(!Objects.isNull(pageable.getSort())){
            Iterator<Sort.Order> orders = pageable.getSort().iterator();
            while (orders.hasNext()){
                Sort.Order order = orders.next();
                Sort sort = new Sort(order);
                query.with(sort);
            }
        }
        long total = mongoTemplate.count(query,documentClass);
        if(total == 0) return new PageImpl<M>(Collections.<M>emptyList(),pageable,total);
        int totalPages = (int) (total + pageable.getPageSize() - 1) / pageable.getPageSize();
        if(pageable.getPageNumber() > (totalPages - 1 ))
            pageable = new PageRequest(totalPages - 1,pageable.getPageSize(),pageable.getSort());
        query.skip(pageable.getOffset()).limit(pageable.getPageSize());
        List<M> subjectList = mongoTemplate.find(query,documentClass);
        return new PageImpl<M>(subjectList,pageable,total);
    }

    default List<M> findAll(MongoTemplate mongoTemplate,Query query,Class<M> documentClass){
        return mongoTemplate.find(query,documentClass);
    }
}
